﻿using ComponentFactory.Krypton.Toolkit;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 查快递的小工具
{
    public partial class MainForm : ComponentFactory.Krypton.Toolkit.KryptonForm
    {
        List<QueryItem> _queryItems = new List<QueryItem>();

        private bool _Stop;

        private delegate void AsynUpdateTextUI(int a, int b);
        private delegate void AsynUpdateProgressBarUI(int a);
        private void UpdateTextUi(int a, int b)
        {
            labelText.Text = string.Format("查询进度: {0}/{1}", a, b);
        }
        private void UpdateProgressBar(int a)
        {
            progressBar.Value = a;
        }

        public MainForm()
        {
            InitializeComponent();
        }




        private async Task RunQuery()
        {
            YTOService ytoService = new YTOService();
            BestService bestService = new BestService();
            int i = 0;
            int total = _queryItems.Count;
            progressBar.Maximum = total;
            foreach (var item in _queryItems)
            {
                if (_Stop)
                {
                    btnStop_Click(null, null);
                    return;
                }
                i++;
                try
                {
                    if (!item.Successful)
                    {
                        if (cbKDCode.Text == "圆通")
                        {
                            await ytoService.GetTrackingInfo(item);
                        }else if (cbKDCode.Text == "百世")
                        {
                            await bestService.GetTrackingInfo(item);
                        }
                    }
                }
                catch(Exception ex)
                {
                    item.Successful = false;
                    item.ErrMsg = ex.Message;
                    item.EndQueryTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                }

                if( i % 10 ==0)
                {
                    labelText.BeginInvoke(new AsynUpdateTextUI(UpdateTextUi), i, total);
                    progressBar.BeginInvoke(new AsynUpdateProgressBarUI(UpdateProgressBar), i);

                }
            }
            labelText.BeginInvoke(new AsynUpdateTextUI(UpdateTextUi), i, total);
            progressBar.BeginInvoke(new AsynUpdateProgressBarUI(UpdateProgressBar), i);
            btnStop_Click(null, null);
        }



        /// <summary>
        /// 转化查询单号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cbKDCode.Text.ToString()))
            {
                MessageBox.Show("先选择快递商");
                return;
            }

            string txtNumbers = txtOddNumbers.Text.Trim();
            if (string.IsNullOrEmpty(txtNumbers))
            {
                MessageBox.Show("没有快递单号");
                return;
            }

            var list = txtNumbers.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            _queryItems = new List<QueryItem>();
            foreach (var _t in list)
            {
                QueryItem item = new QueryItem()
                {
                    TrackingNumber = _t.Trim(),
                    Carrier = cbKDCode.Text.ToString(),
                };
                if (!string.IsNullOrWhiteSpace(item.TrackingNumber))
                {
                    _queryItems.Add(item);
                }
            }
            var dt = DataTableHelper<QueryItem>.ToDataTable(_queryItems);
            queryData.DataSource = dt;
            tabControl1.SelectedIndex = 1;
            RunQuery();
        }


        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExport_Click(object sender, EventArgs e)
        {
            if (_queryItems.Count < 1)
            {
                MessageBox.Show("没有数据");
                return;
            }
            string path = "";
            SaveFileDialog save = new SaveFileDialog();
            save.DefaultExt = "xlsx";
            save.Filter = "Excel File(*.xlsx)|*.xlsx";
            if (save.ShowDialog() == DialogResult.OK)
            {
                path = save.FileName;
                var dt = DataTableHelper<QueryItem>.ToDataTable(_queryItems);
                ExcelHelper.DataTableToExcel(dt, "sheet1", path, true);
                MessageBox.Show("导出成功");
            }
            else
            {
                return;
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            _Stop = true;
            var dt = DataTableHelper<QueryItem>.ToDataTable(_queryItems);
            queryData.DataSource = dt;

        }

        private void btnContinue_Click(object sender, EventArgs e)
        {
            _Stop = false;
            RunQuery();
        }

 
    }
}